/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 62536
 * Date: 2024-02-25
 * Time: 20:20
 */
public class Sort {
    // 归并排序---递归
    public static void mergeSort(int[] array) {
        mergeFunc(array,0,array.length-1);
    }

    private static void mergeFunc(int[] array,int left,int right) {
        if(left >= right) {
            return;
        }
        int mid = left + ((right-left) >> 1);
        mergeFunc(array,left,mid);
        mergeFunc(array,mid+1,right);
        //左边分解完，右边分解完，开始合并
        mergeSort(array,left,mid,right);
    }

    private static void mergeSort(int[] array,int left,int mid,int right) {
        int s1 = left;
        int e1 = mid;
        int s2 = mid+1;
        int e2 = right;
        int[] tmpArr = new int[right-left+1];
        int k = 0;
        //1.保证两个表 都有数据
        while (s1 <= e1 && s2 <= e2) {
            if(array[s1] <= array[s2]) {
                tmpArr[k++] = array[s1++];
            }else {
                tmpArr[k++] = array[s2++];
            }
        }
        //2. 看哪个数组 还有数据 拷贝回去
        while (s1 <= e1) {
            tmpArr[k++] = array[s1++];
        }
        while (s2 <= e2) {
            tmpArr[k++] = array[s2++];
        }
        //3.拷贝到源数组
        for (int i = 0; i < k; i++) {
            array[i+left] = tmpArr[i];
        }
    }

    // 归并排序---非递归
    public void mergeSort2(int[] array){
        // write code  here
        int  gap = 1;
        //最外层循环 控制组数
        while (gap < array.length) {
            //每一组进行排序
            for (int i = 0; i < array.length; i = i+2*gap) {
                int left = i;
                int mid = left + gap-1;
                if(mid >= array.length) {
                    mid = array.length-1;
                }
                int right = mid+gap;
                if(right >= array.length) {
                    right = array.length-1;
                }
                mergeSort(array,left,mid,right);
            }
            gap *= 2;
        }
    }

    // 计数排序
    public void countSort(int[] array){
        // write code  here
        //1.求最值 -> O(n)
        int min = array[0];
        int max = array[0];
        for (int i = 1; i < array.length; i++) {
            if(min > array[i]) {
                min = array[i];
            }
            if(max < array[i]) {
                max = array[i];
            }
        }
        //2、定义计数数组 进行初始化   -> O(n)
        int[] count = new int[max-min+1];

        for (int i = 0; i < array.length; i++) {
            int index = array[i]-min;
            count[index]++;
        }

        //3、遍历计数数组   -> O(max-min) ：max-min-》范围
        int k = 0;//表示array数组的下标
        for (int i = 0; i < count.length; i++) {
            while (count[i] != 0) {
                array[k] = i + min;
                k++;
                count[i]--;
            }
        }
    }
}
